<template>
  <div class="container">
    <el-divider content-position="left"><span class="title-left-color">基本信息</span></el-divider>
    <el-form ref="formRef" :model="form" :rules="rules" v-loading="loading" label-width="150px">
      <el-row :gutter="10">
        <el-col :span="12">
          <el-form-item label="手机号：" prop="mobile">
            <el-input v-model.trim="form.mobile" placeholder="手机号"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="联系人：" prop="username">
            <el-input v-model.trim="form.username" placeholder="联系人"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="法人名称：" prop="legal_person">
            <el-input v-model.trim="form.legal_person" placeholder="法人名称"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="统一社会信用代码：" prop="business_license_number">
            <el-input v-model.trim="form.business_license_number" placeholder="统一社会信用代码"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="开户行：" prop="bank_name">
            <el-input v-model.trim="form.bank_name" placeholder="开户行"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="银行卡号：" prop="bank_account">
            <el-input v-model.trim="form.bank_account" placeholder="银行卡号"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="10">
        <el-col :span="12">
          <el-form-item label="营业执照名称：" prop="company_name">
            <el-input v-model.trim="form.company_name" placeholder="营业执照名称"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="审核结果" prop="usage_status">
            <el-select v-model="form.usage_status" placeholder="请选择审核结果">
              <el-option v-for="item in statusList" :key="item.id" :label="item.dictLabel" :value="item.dictValue"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="10">
        <el-col :span="12">
          <el-form-item label="主营业执照名称：" prop="business_license_cert">
            <UploadImageInfo :imageWidth="178" :imageHeight="178" v-model:disabledbtn="disabledbtn" v-model:loading="loading" imageKey="business_license_cert" v-model:form="form" suggestInfo="建议：尺寸750x530像素(等比例亦可)，大小500k以下" />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <el-divider content-position="left"><span class="title-left-color">其他信息</span></el-divider>
    <div style="margin: 0 70px">
      <el-descriptions :column="2" size="default">
        <el-descriptions-item label="申请时间">{{ handleVerifyFormatDate(form.add_time) }}</el-descriptions-item>
      </el-descriptions>
    </div>
    <div class="footer-center">
      <el-button :disabled="disabledbtn" @click="cancelSubmit">取 消</el-button>
      <el-button type="primary" :disabled="disabledbtn" v-if="!isDisabledbtn" @click="submitForm">确 定</el-button>
    </div>
  </div>
</template>

<script setup lang="ts">
import UploadImageInfo from "@/components/common/UploadImageInfo.vue";
import { handleVerifyFormatDate } from "@/utils/utils";
import type { postOrPutType } from "@/constants";
import type { HasId, ViewMode } from "@/types/common";
import { useState } from "@/hooks/useState.ts";
import type { IDictData } from "@/types/dict";
import type { IOperatorManager } from "@/types/user/operatorManager";
import { commonOperatorInfo, getOperatorByIdInfo } from "@/utils/api/admin/merchant/operator";
const { disabledbtn, loading, toggleState } = useState();

interface Props {
  id: number;
  statusList: Array<IDictData>;
}
const { id, statusList } = defineProps<Props>();
const formStatus = defineModel<ViewMode>("formStatus", { required: true });

const emit = defineEmits<{
  handleInitData: [];
  handleSuccess: [];
}>();

const isDisabledbtn = ref(false);
const formRef = useTemplateRef("formRef");
const methodType = ref<postOrPutType>("PUT");

const rules = reactive({
  mobile: [{ required: true, message: "请填写手机号", trigger: "blur" }],
  username: [{ required: true, message: "请填写联系人", trigger: "blur" }],
  company_name: [{ required: true, message: "请填写联系人", trigger: "blur" }],
  legal_person: [{ required: true, message: "请填写法人名称", trigger: "blur" }],
  business_license_number: [{ required: true, message: "请填写统一社会信用代码", trigger: "blur" }],
  bank_name: [{ required: true, message: "请填写开户行", trigger: "blur" }],
  bank_account: [{ required: true, message: "请填写银行卡号", trigger: "blur" }],
  business_license_cert: [{ required: true, message: "请上传营业执照", trigger: "blur" }],
  usage_status: [{ required: true, message: "请选择审核状态", trigger: "blur" }]
});
const form = reactive<IOperatorManager>({
  id: 0,
  username: "",
  mobile: "",
  legal_person: "",
  company_name: "",
  business_license_cert: "",
  business_license_number: "",
  bank_account: "",
  bank_name: "",
  usage_status: "",
  add_time: 0
});
onMounted(() => {
  console.log("Component mounted!");
});

/* formStatus处理器 */
const statusHandlers: Record<ViewMode, () => void> = {
  view: () => {
    isDisabledbtn.value = true;
  },
  edit: () => {
    methodType.value = "PUT";
  },
  add: () => {
    methodType.value = "POST";
  },
  none: () => {
    /* 初始化数据 */
    handleInitData();
  }
};
/* 监听formStatus,新增，编辑，查看的时候都可以打开模态框，又是有不同的操作和效果，需要单独判断，none为模态框关闭的情况，需要初始化数据 */
watch(formStatus, newValue => {
  const handler = statusHandlers[newValue];
  handler?.();
});
watch(
  () => id,
  newValue => {
    if (newValue == 0) {
      /* 初始化数据 */
    } else {
      form.id = newValue;
      handleGetInfoById(id);
    }
  }
);
/* 通过id获取情信息 */
function handleGetInfoById(id: number) {
  toggleState(true);
  getOperatorByIdInfo<IOperatorManager, HasId>({ id })
    .then(res => {
      form.id = res.result.id;
      form.username = res.result.username;
      form.mobile = res.result.mobile;
      form.legal_person = res.result.legal_person;
      form.company_name = res.result.company_name;
      form.business_license_cert = res.result.business_license_cert;
      form.business_license_number = res.result.business_license_number;
      form.bank_account = res.result.bank_account;
      form.bank_name = res.result.bank_name;
      form.usage_status = res.result.usage_status;
      form.add_time = res.result.add_time;
    })
    .catch(() => {})
    .finally(() => {
      toggleState(false);
    });
}

/* 初始化数据 */
function handleInitData() {
  form.add_time = new Date().getTime() / 1000;
  methodType.value = "POST";
  isDisabledbtn.value = false;
  formRef.value?.resetFields();
  formRef.value?.clearValidate();
}

/* 保存或编辑 */
function submitForm() {
  if (!formRef.value) return;
  formRef.value.validate(valid => {
    if (!valid) {
      ElMessage.warning("请填写必填字段");
      return;
    }
    submitFormInfo();
  });
}

/* 保存或编辑信息 */
function submitFormInfo() {
  /* 防止多次提交 */
  toggleState(true);
  commonOperatorInfo(form, methodType.value)
    .then(res => {
      ElMessage.success(res.msg);
      cancelSubmit();
      emit("handleSuccess");
    })
    .catch(() => {})
    .finally(() => {
      toggleState(false);
    });
}
/* 保存或编辑 取消提交 */
function cancelSubmit() {
  emit("handleInitData");
}
</script>

<style lang="scss" scoped>
/* 修改select的盒模型 */
.el-select {
  display: block;
}
/* 底部按钮居中 */
.footer-center {
  margin: 10px 0;
  text-align: center;
}

.w-continer {
  display: flex;
  align-items: center;
  gap: 10px;
}
.draggable-info {
  display: flex;
  align-items: center;
  gap: 10px;
}

.recovery-valuation-info {
  margin: 20px 50px;
  .r-title {
    margin-bottom: 20px;
    margin-left: 20px;
    font-weight: bold;
  }
}
</style>
